package com.aiapphub.BaseCode.handler.security;

import com.alibaba.fastjson.JSON;
import com.aiapphub.BaseCode.common.ResponseResult;
import com.aiapphub.BaseCode.constants.AppHttpCodeEnum;
import com.aiapphub.BaseCode.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    /**
     * 认证失败处理器
     * 如果认证异常是 BadCredentialsException，则返回包含错误代码和异常消息的错误结果；
     * 如果是 InsufficientAuthenticationException，则返回需要登录的错误结果；
     * 否则返回内部服务器错误的错误结果.
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        authException.printStackTrace();
        //InsufficientAuthenticationException：未登录异常
        //BadCredentialsException：坏的凭证异常
        ResponseResult result = null;
        if(authException instanceof BadCredentialsException){
            //返回包含错误代码和异常消息的错误结果
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),authException.getMessage());
        }else if(authException instanceof InsufficientAuthenticationException){
            //返回需要登录的错误结果
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else{
            //返回内部服务器错误的错误结果
            result = ResponseResult.errorResult(AppHttpCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"认证或授权失败");
        }
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
